package com.bidevalution.business.impl;

import com.bidevalution.business.context.UserRoleType;
import com.bidevalution.business.service.*;
import com.bidevalution.dao.entity.BeSectionDecrypt;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.dao.entity.BeSectionStepJob;
import com.bidevalution.dao.jdbc.ExecuteStoredProcedure;
import com.bidevalution.dao.mapper.BeSectionInfoMapper;
import com.bidevalution.dao.mapper.BeSectionParamsMapper;
import com.bidevalution.dao.mapper.BeSectionStepJobMapper;
import com.bidevalution.support.context.Constants;
import com.bidevalution.support.context.SectionStateEnum;
import com.ggzy.tongyi.dubbo.api.EnterPriseInfoDubboService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qtp.auth.api.ParamsService;
import com.qtp.common.core.TSUser;
import com.qtp.core.model.Paging;
import com.qtp.core.model.Response;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.OConvertUtils;
import com.qtp.user.models.SysParams;
import org.apache.commons.lang3.StringUtils;
import org.hsqldb.DatabaseType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取标段信息接口实现类
 *
 * @author shenhui
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BeSectionInfoServiceImpl implements BeSectionInfoService {

    @Autowired
    private BeSectionInfoMapper beSectionInfoMapper;
    @Autowired
    private EnterPriseInfoDubboService enterPriseInfoDubboService;
    @Autowired
    private BeSectionParamsMapper beSectionParamsMapper;
    @Autowired
    private BeSectionDecryptService beSectionDecryptService;
    @Autowired(required = false)
    private ParamsService paramsService;
    @Autowired
    private BeSectionStepJobMapper beSectionStepJobMapper;
    @Value("${spring.datasource.username}")
    private String userName;
    @Value("${spring.datasource.driver-class-name}")
    private String driverName;
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.password}")
    private String password;
    /**
     * 获取今日开标/历史开标数据
     *
     * @param paramsMap
     * @return
     * @throws Exception
     */
    @Override
    public Paging<List<BeSectionInfo>> getBeSectionListPaging(Map<String, Object> paramsMap) throws Exception {
        String sectionName = "%" + OConvertUtils.getString(paramsMap.get("sectionName")) + "%";
        paramsMap.put("sectionName", sectionName);
        Map<String, Object> enterParams = new HashMap<>();
        enterParams.put("ep_guid", paramsMap.get("enterpriseId"));
        // 获取企业组织机构代码
        Response<Map<String, Object>> response = enterPriseInfoDubboService.getEnterInfo(enterParams);
        String orgCode = "";
        if (response != null && response.isSuccess() && response.getResult() != null) {
            orgCode = OConvertUtils.getString(response.getResult().get("ep_org_code"));
        }
        // 获取分页参数
        int limit = OConvertUtils.getInt(paramsMap.get("rp"), 10);
        int page = OConvertUtils.getInt(paramsMap.get("page"), 1);
        Page<BeSectionInfo> beSectionInfoPage = PageHelper.startPage(page, limit);
        Integer type = OConvertUtils.getInt(paramsMap.get("type"));
        boolean isEnterUserType = Boolean.parseBoolean(OConvertUtils.getString(paramsMap.get("isEnterUserType")));
        String enterpriseId = OConvertUtils.getString(paramsMap.get("enterpriseId"));
        List<BeSectionInfo> list = beSectionInfoMapper.getBeSectionList(type, sectionName, isEnterUserType, orgCode,
                enterpriseId);
        return new Paging(beSectionInfoPage.getTotal(), list);

    }

    /**
     * 根据id获取标段信息
     *
     * @param seqId
     * @return
     */
    @Override
    public BeSectionInfo getBeSectionInfoById(String seqId) {
        return beSectionInfoMapper.selectByPrimaryKey(seqId);
    }

    /**
     * 更新标段状态
     *
     * @param sectionId
     * @param sectionStage
     * @return
     */
    @Override
    public Boolean updateSectionStage(String sectionId, String sectionStage) throws Exception {
        if (beSectionInfoMapper.updateSectionStage(sectionId, sectionStage) > 0) {
            if (SectionStateEnum.decrypting.getValue().equals(sectionStage)) {
                Date now = new Date();
                // 新增解密开始时间
                beSectionParamsMapper.insertBeSectionParams(sectionId, "decryptStartTime",
                        DateUtil.dateToString(now, DateUtil.PT2));
                SysParams sysParams = paramsService.querySysParamsByCode("decryptTime");
                if (sysParams != null) {
                    // 新增解密截止时间
                    beSectionParamsMapper.insertBeSectionParams(sectionId, "decryptEndTime",
                            DateUtil.dateToString(DateUtil.getAfterMinute(now, Integer.valueOf(sysParams.getSypaValue())), DateUtil.PT2));
                }
            }
            return true;
        }

        return false;
    }

    @Override
    public List<BeSectionInfo> getLiveBeSectionList() {
        return beSectionInfoMapper.getLiveBeSectionList();
    }

    @Override
    public List<BeSectionInfo> getLiveListByRoom(String roomName) {
        return beSectionInfoMapper.getLiveListByRoom(roomName);
    }

    @Override
    public List<BeSectionInfo> getChatSectionList() {
        return beSectionInfoMapper.getChatSectionList();
    }

    @Override
    public Paging<List<BeSectionInfo>> getAllList(Map<String, Object> paramsMap) throws Exception {
        // 获取分页参数
        int limit = OConvertUtils.getInt(paramsMap.get("rp"), 10);
        int page = OConvertUtils.getInt(paramsMap.get("page"), 1);
        Page<BeSectionInfo> beSectionInfoPage = PageHelper.startPage(page, limit);
        String sectionName = null;
        if (StringUtils.isNotBlank(OConvertUtils.getString(paramsMap.get("sectionName")))) {
            sectionName = "%" + OConvertUtils.getString(paramsMap.get("sectionName")) + "%";
        }
        Map<String, Object> enterParams = new HashMap<>();
        enterParams.put("ep_guid", paramsMap.get("enterpriseId"));
        // 获取企业组织机构代码
        Response<Map<String, Object>> response = enterPriseInfoDubboService.getEnterInfo(enterParams);
        String orgCode = null;
        if (response != null && response.isSuccess() && response.getResult() != null) {
            orgCode = OConvertUtils.getString(response.getResult().get("ep_org_code"));
        }
        List<BeSectionInfo> list = beSectionInfoMapper.getAllList(sectionName, orgCode);
        return new Paging(beSectionInfoPage.getTotal(), list);
    }

    @Override
    public UserRoleType getUserRoleType(String sectionId, TSUser loginUser, List<String> roleList) throws Exception {
        for (String role : roleList) {
            if (UserRoleType.JGRY.getValue().equals(role)) {
                // 监管人员
                return UserRoleType.JGRY;
            } else if (UserRoleType.JYXRY.getValue().equals(role)) {
                // 中心人员
                return UserRoleType.JYXRY;
            } else if (UserRoleType.ZBDL.getValue().equals(role) || UserRoleType.ZBR.getValue().equals(role)
                    || UserRoleType.TBR.getValue().equals(role)) {
                Map<String, Object> params = new HashMap<>();
                params.put("ep_guid", loginUser.getOrgId());
                // 获取请求中的参数
                Response<Map<String, Object>> response = enterPriseInfoDubboService.getEnterInfo(params);
                // 获取当前用户组织机构代码
                String orgCode = "";
                if (response.getResult() != null) {
                    orgCode = String.valueOf(response.getResult().get("ep_org_code"));
                }
                // 判断是否是招标代理
                BeSectionInfo beSectionInfo = getBeSectionInfoById(sectionId);
                if (beSectionInfo != null && orgCode.equals(beSectionInfo.getAgentOrgCode())) {
                    return UserRoleType.ZBDL;
                }
                // 判断是否是投标单位
                BeSectionDecrypt beSectionDecrypt = beSectionDecryptService.getBeSectionDecryptInfoByCode(sectionId, orgCode);
                if (beSectionDecrypt != null) {
                    return UserRoleType.TBR;
                }

            }
        }
        return null;
    }

    /**
     * 获取今日开标项目数据
     *
     * @return
     */
    @Override
    public List<BeSectionInfo> getTodaySectionList() {
        return beSectionInfoMapper.getTodaySectionList();
    }

    @Override
    public List<BeSectionInfo> getAgentSectionList(Map<String, Object> paramsMap) throws Exception {
        //获取查询条件
        String sectiName = OConvertUtils.getString(paramsMap.get("sectiName"));
        String sectiCode = OConvertUtils.getString(paramsMap.get("sectiCode"));
        String orgCode = OConvertUtils.getString(paramsMap.get("orgCode"));
        String startTime = OConvertUtils.getString(paramsMap.get("startTime"));
        String endTime = OConvertUtils.getString(paramsMap.get("endTime"));
        List<BeSectionInfo> sectionList = beSectionInfoMapper.getAgentSectionList(sectiName, sectiCode, orgCode, startTime, endTime);
        return sectionList;
    }

    /**
     * 获取专家权限下今日评审项目列表
     * @param loginName 专家登录名
     * @return
     * @throws Exception
     */
    @Override
    public List<BeSectionInfo> getExpertSectionList(String loginName) throws Exception {
        return beSectionInfoMapper.getExpertSectionList(loginName);
    }

	@Override
	public List<BeSectionInfo> getListByBidOpenTime(Date startDate, Date endDate) {
		// TODO Auto-generated method stub
		return beSectionInfoMapper.getListByBidOpenTime(startDate, endDate);
	}

	@Override
	public List<BeSectionInfo> getAllSectionList(String orgCode,String areaId, String sectionName, String sectionCode) {

		return beSectionInfoMapper.getAllSectionList(orgCode,areaId, sectionName,sectionCode);
	}

    @Override
    public Response<String> updateReviewStart(String sectionId) throws Exception {
        BeSectionInfo beSectionInfo = new BeSectionInfo();
        beSectionInfo.setSeqId(sectionId);
        beSectionInfo.setReviewState(2);
        beSectionInfo.setUpdateTime(DateUtil.now());
        //更新标段评审状态为可以评审
        if (beSectionInfoMapper.updateByPrimaryKeySelective(beSectionInfo) < 1) {
            throw new Exception("更新标段评审状态失败！");
        }
        //更新需要提前执行任务的状态为可以执行
        BeSectionStepJob beSectionStepJob = new BeSectionStepJob();
        beSectionStepJob.setSectionId(sectionId);
        beSectionStepJob.setIsAdvanceExecute(Constants.STATE_Y);
        //2表示可以执行（用于提前执行的任务）
        beSectionStepJob.setJobState(Constants.TWO);
        beSectionStepJob.setUpdateTime(DateUtil.now());
        //更新标段环节任务状态为可以执行
        if (beSectionStepJobMapper.updateStepJobBySectionId(beSectionStepJob) < 1) {
            return Response.fail("正在同步环节数据，请稍候...");
        }
        return Response.ok();
    }

    @Override
    public boolean updateSectionInfoById(String sectionId) throws Exception {
        BeSectionInfo beSectionInfo = new BeSectionInfo();
        beSectionInfo.setSeqId(sectionId);
        beSectionInfo.setReviewState(Constants.THREE);
        beSectionInfo.setReviewEndTime(DateUtil.now());
        beSectionInfo.setUpdateTime(DateUtil.now());
        //更新标段评审状态为评审结束
        if (beSectionInfoMapper.updateByPrimaryKeySelective(beSectionInfo) < 1) {
            return false;
        }
        return true;
    }

	@Override
	public BeSectionInfo selectByCode(String code) {
		// TODO Auto-generated method stub
		return beSectionInfoMapper.getSectionInfoByCode(code);
	}
    @Override
    public Response deleteBySectionId(String sectionId) {
        BeSectionInfo sectionInfo = beSectionInfoMapper.getSectionInfoById(sectionId);
        String sql="{call delStep(?)}";
        Object [] params = {sectionId};
        ExecuteStoredProcedure procedure = new ExecuteStoredProcedure(url, driverName, userName, password);
        procedure.executeUpdate(sql, params);
        sql="{call delPro(?)}";
        Object [] params2 = {sectionInfo.getTdProjectid()};
        return procedure.executeUpdate(sql, params2);
    }
    @Override
    public Response deleteEnterprise(String sectionId, String enterpriseId) {
        BeSectionInfo sectionInfo = beSectionInfoMapper.getSectionInfoById(sectionId);
        String sql="{call delStepByEnterprise(?,?)}";
        Object [] params = {sectionId,enterpriseId};
        ExecuteStoredProcedure procedure = new ExecuteStoredProcedure(url, driverName, userName, password);
        procedure.executeUpdate(sql, params);
        Object [] params2 = {sectionInfo.getTdProjectid(),enterpriseId};
        sql="{call delProByEnterprise(?,?)}";
        return procedure.executeUpdate(sql, params2);
    }
}
